package com.zork.cmdb.webapi.common.filter;

import com.zork.cmdb.webapi.domain.dto.AccessDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Order(1)
@WebFilter(filterName = "accessFilter", urlPatterns = "/*")
public class AccessFilter implements Filter {

    private static final String REJECT_URI = "/reject";

    @Autowired
    private AccessDTO accessDTO;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        boolean flag = false;
        for (AccessDTO.RuleList ruleList:accessDTO.getRuleList()) {
            if (url.startsWith(ruleList.getUrl()) && ruleList.getIp().contains(ip) && isBelong(ruleList.getStartTime(), ruleList.getEndTime())) {
                flag = true;
                break;
            }
        }
        if (flag) {
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            servletRequest.getRequestDispatcher(REJECT_URI).forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    public static boolean isBelong(String startTime,String endTime){
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date now =null;
        Date begin = null;
        Date end = null;
        try {
            now = df.parse(df.format(new Date()));
            begin = df.parse(startTime);
            end = df.parse(endTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return belongCalendar(now, begin, end);
    }
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
}
